/*
 * QueueLauncher.h
 *
 */

#ifndef QUEUELAUNCHER_H_
#define QUEUELAUNCHER_H_

#include "../common/Argv.h"
#include "../IPC/MessageQueue.h"
#include "../IPC/ProcessAux.h"
#include "../common/IPCUids.h"
#include "../../channel_common/routing_tables/RoutingService.h"
#include "../channel_common/agent_address_service/AgentAddressService.h"

namespace servicios_distribuidos{
typedef enum{QUEUE_SEND=0,QUEUE_RECV}QueueType;

class QueueLauncher{
public:

template<class T>
static void createDistributedQueue(std::string queuePath,
						   char queueKey,
						   std::string hostName,
						   QueueType queueType,
						   int mType=0)
{
	ipc::MessageQueue<T>::createNonExclusive(queuePath, queueKey);

	if(queueType ==QUEUE_SEND)
	{
		Argv args;
		args.pushArg(hostName);
		args.pushArg(queuePath);
		args.pushArg(queueKey);
		args.pushArg(sizeof(T));
		args.pushArg(mType);
		ProcessAux::launchProcess2("./out/mq_mux",1,args);
	}
	else
	{
		Argv args;
		args.pushArg(hostName);
		args.pushArg(queuePath);
		args.pushArg(queueKey);
		args.pushArg(sizeof(T));
		args.pushArg(mType);
		ProcessAux::launchProcess2("./out/mq_demux",1,args);
	}
};

template<class T>
static void createDistributedQueueByUid(Uid uid,
							std::string hostName,
							QueueType queueType,
							int mType=0)
{
	QueueLauncher::createDistributedQueue<T>(
			IPCUids::getFile(uid)+hostName,
			IPCUids::getKey(uid),
			hostName,
			queueType,
			mType
	);
};

template<class T>
static void createDynamicDistributedQueueByUid(Uid uid,
							std::string hostName,
							QueueType queueType,
							int mType=0)
{
	std::string queuePath = IPCUids::getFile(uid);
	char queueKey = IPCUids::getKey(uid);

	ipc::MessageQueue<T>::createNonExclusive(queuePath+hostName, queueKey);

	if(queueType ==QUEUE_SEND)
	{
		Argv args;
		args.pushArg(hostName);
		args.pushArg(queuePath);
		args.pushArg(queueKey);
		args.pushArg(sizeof(T));
		args.pushArg(mType);
		ProcessAux::launchProcess2("./out/mq_mux_dyn",1,args);
	}
	else
	{
		int mTypeCapaN = mType;
		int mTypeCapaN_1 = channel::AgentAddressService::registerQueueAgent
							(queuePath,queueKey,mTypeCapaN);

		channel::RoutingService::registerAgent(hostName,
								StringUtils::NumberToString(mTypeCapaN_1));

		Argv args;
		args.pushArg(hostName);
		args.pushArg(queuePath);
		args.pushArg(queueKey);
		args.pushArg(sizeof(T));
		args.pushArg(mType);
		ProcessAux::launchProcess2("./out/mq_demux_dyn",1,args);
	}
};


};//End class

};//End namespace
#endif /* QUEUELAUNCHER_H_ */
